package top.ivansong92.ms.filenas.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.ivansong92.ms.filenas.service.FileService;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("file")
public class FileController {

    @Autowired
    private FileService fileService;

    @PostMapping(value = "upload")
    public Map<String, Object> upload(@RequestParam(name = "file", required = false) MultipartFile file) {
        Map<String, Object> res = new HashMap<>();
        if (file == null || file.isEmpty()) {
            res.put("success", false);
            res.put("info", "file is empty");
            return res;
        }
        String fileName = UUID.randomUUID().toString();
        try (InputStream inputStream = file.getInputStream();
             FileOutputStream outputStream = new FileOutputStream(new File(fileName))) {
            byte buffer[] = new byte[1024];
            int length = 0;
            while ((length = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, length);
            }
            fileService.saveFile(file.getOriginalFilename(), fileName, file.getContentType());
            res.put("success", true);
            return res;
        } catch (Exception e) {
            res.put("success", false);
            res.put("info", "file upload error");
            return res;

        }
    }


    @GetMapping(value = "{id}/download")
    public void download(@PathVariable("id") long id, HttpServletResponse response) {
        try (FileInputStream inputStream = new FileInputStream(new File("23306a2b-855c-442c-b660-84f6e992fd09"));
             OutputStream os = response.getOutputStream()) {
            String filename = "123.jpeg";
            response.addHeader("Content-Disposition", "attachment;filename=" + filename);
            response.setContentType("image/jpeg");

            byte buffer[] = new byte[1024];
            int length = 0;
            while ((length = inputStream.read(buffer)) > 0) {
                os.write(buffer, 0, length);
            }

        } catch (Exception e) {

        }
    }

    @RequestMapping(value = "list", method = {RequestMethod.GET, RequestMethod.POST})
    public Map<String, Object> fileList() {
        return Collections.emptyMap();
    }

}
